package com.xxiongb.business;

import java.io.IOException;
import java.util.Base64;
import java.util.List;

import com.xxiongb.business.constant.AppConstants;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpServiceGenerator {
	public static final String API_BASE_URL0 = "http://127.0.0.1:8999";
	public static final String API_BASE_URL1 = "http://127.0.0.1:9005";

	private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

	private static Retrofit.Builder builder0 = new Retrofit.Builder().baseUrl(API_BASE_URL0)
			.addConverterFactory(GsonConverterFactory.create());
	
	private static Retrofit.Builder builder1 = new Retrofit.Builder().baseUrl(API_BASE_URL1)
			.addConverterFactory(GsonConverterFactory.create());


	public static <S> S createService(Class<S> serviceClass, String username, String password) {
		S s = null;
		if (username != null && password != null) {
			synchronized (HttpServiceGenerator.class) {
				List<?> ins = httpClient.interceptors();
				if(ins.size() > 0){
					ins.clear();
				}
			}
			
			MyInterceptor interceptor = new MyInterceptor();
			interceptor.username = "yiyi";
			interceptor.password = "123456";
			interceptor.status = MyInterceptor.MYINTERCEPTOR_GENERATOR_TAKEN;
			httpClient.addInterceptor(interceptor);

			OkHttpClient client = httpClient.build();
			Retrofit retrofit = builder0.client(client).build();
			s = retrofit.create(serviceClass);
		}

		return s;
	}

	
	
	public void clearInterceptor(){
		synchronized (HttpServiceGenerator.class) {
			List<?> ins = httpClient.interceptors();
			if(ins.size() > 0){
				ins.clear();
			}
		}
	}
	
	public static String base64encoder(byte[] content) {
		Base64.Encoder encoder = Base64.getEncoder();
		return encoder.encodeToString(content);
	}
	
	private static class MyInterceptor implements Interceptor {

		public final static int MYINTERCEPTOR_GENERATOR_TAKEN = 0;
		public final static int MYINTERCEPTOR_REFRESH_TAKEN = 1;
		public final static int MYINTERCEPTOR_HOLD_TAKEN = 2;

		public int status = MYINTERCEPTOR_REFRESH_TAKEN;

		public String authToken;
		public String refreshToken;
		
		public String username;
		public String password;

		@Override
		public Response intercept(Chain chain) throws IOException {

			Request original = chain.request();
			Request.Builder requestBuilder = original.newBuilder();
			requestBuilder.header("Content-Type", "application/json;charset=UTF-8");
			Response response = null;
			
			switch (status) {
			case MYINTERCEPTOR_GENERATOR_TAKEN:
				RequestBody formBody = new FormBody.Builder()
				.add("username", username)
				.add("password", password)
				.add("grant_type", "password")
				.add("scope", "openid")
				.add("client_id", AppConstants.APP_CLIENT)
				.add("client_secret", AppConstants.APP_SECRET).build();
				String authHeader = "Basic "
						+ base64encoder((AppConstants.APP_CLIENT + ":" + AppConstants.APP_SECRET).getBytes());
				requestBuilder.header("Authorization", authHeader).post(formBody);
				break;
			case MYINTERCEPTOR_REFRESH_TAKEN:
				RequestBody refreshformBody = new FormBody.Builder()
				.add("grant_type", "refresh_token")
				.add("scope", "openid")
				.add("refresh_token", refreshToken).build();
				String refreshHeader = "Basic "
						+ base64encoder((AppConstants.APP_CLIENT + ":" + AppConstants.APP_SECRET).getBytes());
				requestBuilder.header("Authorization", refreshHeader).post(refreshformBody);
				break;
			case MYINTERCEPTOR_HOLD_TAKEN:
			default:
				requestBuilder.header("Authorization", "Bearer "+authToken);
				//TODO 如果token过期，自动重连
				Request request = requestBuilder.build();
				response = chain.proceed(request);
				break;
			}

			if(response == null){
				Request request = requestBuilder.build();
				response = chain.proceed(request);
			}
			return response;
		}

	}
}
